<template>
  <div class="page-container">
    <card class="add-info-card" title="基本信息" toggle :showDivider="false">
      <a-spin :loading="spinning">
        <page-form :model="form" layout="vertical" ref="formRef" :rules="rules">
          <page-form-item field="brandId" label="品牌" :disabled="id" required>
            <remote-select
              v-model="form.brandId"
              :params="{
                id: form.brandId,
              }"
              type="car_brand_saasList"
              @change="brandChange"
            />
          </page-form-item>
          <page-form-item field="seriesId" label="车系" :disabled="id" required>
            <remote-select
              v-model="form.seriesId"
              :params="{
                brandId: form.brandId,
                id: form.seriesId,
              }"
              type="car_series_saasList"
              @change="seriesChange"
            />
          </page-form-item>
          <page-form-item field="modelId" label="车型" :disabled="id" required>
            <remote-select
              v-model="form.modelId"
              :params="{
                brandId: form.brandId,
                seriesId: form.seriesId,
              }"
              type="car_model_saasList"
              @change="modelChange"
            />
          </page-form-item>
          <page-form-item field="yearStyleName" label="年款">
            <div class="w-full" @click.stop="alertMsg">
              <a-input v-model="carModelInfo.yearStyleName" disabled />
            </div>
          </page-form-item>
          <page-form-item field="driveTypeStr" label="驱动方式">
            <div class="w-full" @click.stop="alertMsg"> <a-input v-model="carModelInfo.driveTypeStr" disabled /> </div>
          </page-form-item>
          <page-form-item field="gearboxTypeStr" label="变速箱">
            <div class="w-full" @click.stop="alertMsg"> <a-input v-model="carModelInfo.gearboxTypeStr" disabled /></div>
          </page-form-item>
          <page-form-item field="fuelOilTypeStr" label="能源类型">
            <div class="w-full" @click.stop="alertMsg"> <a-input v-model="carModelInfo.fuelOilTypeStr" disabled /></div>
          </page-form-item>
          <page-form-item field="outputVolume" label="排量" v-if="+carModelInfo.fuelOilType !== 0">
            <div class="w-full" @click.stop="alertMsg"> <a-input v-model="carModelInfo.outputVolume" disabled /></div>
          </page-form-item>
          <page-form-item field="fuelGradeStr" label="燃料标号" v-if="+carModelInfo.fuelOilType !== 0">
            <div class="w-full" @click.stop="alertMsg"> <a-input v-model="carModelInfo.fuelGradeStr" disabled /></div>
          </page-form-item>
          <page-form-item field="doorCount" label="车门数">
            <div class="w-full" @click.stop="alertMsg"> <a-input-number v-model="carModelInfo.doorCount" disabled /></div>
          </page-form-item>
          <page-form-item field="seatNum" label="座位数">
            <div class="w-full" @click.stop="alertMsg"> <a-input-number v-model="carModelInfo.seatNum" disabled /></div>
          </page-form-item>
          <page-form-item field="sortIdList" label="车型分类" labelTooltipContent="车型分类用于自营小程序中，选择车型时的归类">
            <sysdict-select v-model="form.sortIdList" code="car_model_tenant_sort" multiple />
          </page-form-item>
        </page-form>
      </a-spin>
      <a-divider class="custom-divider" />
    </card>
    <card class="add-info-card" title="车型图片" toggle :showDivider="false">
      <a-alert>
        <template #icon>
          <icon-exclamation-circle />
        </template>
        支持 .jpg、.jpeg、.png 格式，建议分辨率300*225，建议图片文件大小不超过 8MB，注意遮挡牌照.
      </a-alert>
      <div class="upload-wrapper">
        <upload-img title="缩略图" :showTit="false" v-model="form.modelImgId" tooltip="缩略图" single margin />
        <upload-img title="整车图" :showTit="false" v-model="form.modelImgCarId" tooltip="整车图" single margin />
        <upload-img title="细节图" :showTit="false" v-model="form.modelImgDetailIdList" tooltip="细节图" margin />
      </div>
    </card>
  </div>
  <page-form-footer :ok-loading="loading" @ok="saveCarModel" height="0" />
</template>

<script setup name="CarModelForm">
  import { ref, reactive, onMounted } from 'vue'
  import { useRoute } from 'vue-router'
  import { getCarModelAdd, getCarModelEdit, getCarModelDetail, getSysCarModelDetail } from '@/api/asset/carModel'
  import { Message } from '@arco-design/web-vue'
  import useNavigate from '@/hooks/useNavigate'

  const { navigateBack } = useNavigate()
  const route = useRoute()

  const rules = ref({
    brandId: { required: true, message: '请选择', trigger: 'change' },
    seriesId: { required: true, message: '请选择', trigger: 'change' },
    modelId: { required: true, message: '请选择', trigger: 'change' },
  })

  const id = ref(route.params?.id || null)
  const form = reactive({}) // 编辑信息
  const carModelInfo = ref({}) // 车型信息

  // 品牌change
  const brandChange = () => {
    form.seriesId = undefined
    form.modelId = undefined
    form.modelName = undefined
    formRef.value.clearValidate()
    getSysCarModelDetailFn()
  }
  // 车系change
  const seriesChange = (val, option) => {
    // 清空不反选
    if (val) {
      form.brandId = option.brandId
    }
    form.modelId = undefined
    form.modelName = undefined
    // 清空检验
    formRef.value.clearValidate()
    getSysCarModelDetailFn()
  }
  // 车型change
  const modelChange = (val, option) => {
    // 反选上级，清空不反选
    if (val) {
      form.brandId = option.brandId
      form.seriesId = option.seriesId
    }
    form.modelName = option.modelName
    // 清空检验
    formRef.value.clearValidate()
    getSysCarModelDetailFn(val)
  }

  // 获取系统车型详情
  const getSysCarModelDetailFn = (id) => {
    if (!id) {
      carModelInfo.value = {}
      return
    }
    loading.value = true
    getSysCarModelDetail({ id }).then((res) => {
      loading.value = false
      carModelInfo.value = res.result
    })
  }

  // 商户车型详情
  const spinning = ref(false)
  const getCarModelDetailFn = (id) => {
    spinning.value = true
    getCarModelDetail({ id }).then(({ result }) => {
      spinning.value = false
      carModelInfo.value = result
      Object.assign(form, result)
      const { modelImgIdList, modelImgCarIdList, modelImgDetailIdList } = result
      form.modelImgId = modelImgIdList?.length > 0 ? modelImgIdList[0] : ''
      form.modelImgCarId = modelImgCarIdList?.length > 0 ? modelImgCarIdList[0] : ''
      form.modelImgDetailIdDataList = modelImgDetailIdList || []
    })
  }

  //  保存
  const formRef = ref(null)
  const loading = ref(false)
  const saveCarModel = (noticeSuccess) => {
    formRef.value.validate((error) => {
      if (!error) {
        // fetch api方法
        let fetch = getCarModelEdit
        const { sortIdList, modelImgId, modelImgCarId, modelImgDetailIdList, modelId, modelName, modelGrade } = form
        let formData = {
          sortIdList,
          modelImgIdList: modelImgId ? [modelImgId] : undefined,
          modelImgCarIdList: modelImgCarId ? [modelImgCarId] : undefined,
          modelImgDetailIdList,
          id: id.value,
        }
        // 新增
        if (!id.value) {
          formData.modelId = modelId
          formData.modelName = modelName
          formData.modelGrade = modelGrade
          fetch = getCarModelAdd
        }
        loading.value = true
        fetch(formData).then(() => {
          // 成功提示
          noticeSuccess()
          navigateBack()
        })
        loading.value = false
      }
    })
  }

  // 提示
  const alertMsg = () => {
    Message.warning('新增车型后，无法修改。如要使用新的车型信息，请新增新的车型')
  }

  onMounted(() => {
    // 编辑
    if (id.value) {
      getCarModelDetailFn(id.value)
    }
  })
</script>
<style lang="less" scoped>
  .add-info-card {
    .custom-divider {
      margin: 0 0 20px;
    }
  }
  .upload-wrapper {
    display: flex;
  }
</style>
